package com.mingrisoft;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.mingrisoft.database.DBOpenHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends Activity implements View.OnClickListener {
    /**
     * Called when the activity is first created.
     */
    private EditText editUserName, editUserPass;
    private ListView testListView;
    /*定义数据库所需成员变量 */
    private DBOpenHelper dbOpenHelper;
    private Cursor cursor;
    //数据库里存储的password
    String dbpassword, key;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editUserName = (EditText) findViewById(R.id.userNameEditText);
        editUserPass = (EditText) findViewById(R.id.passwordEditText);
        testListView = (ListView) findViewById(R.id.testListView);
        CheckBox checkBoxRemeberPass = (CheckBox) findViewById(R.id.rememberMsgCheckBox);
        TextView tvSeekPass = (TextView) findViewById(R.id.seekBackPassword);
        Button btnLogin = (Button) findViewById(R.id.loginButton);
        Button btnRegister = (Button) findViewById(R.id.registerButton);
        checkBoxRemeberPass.setOnCheckedChangeListener(new MyCheckBoxLisenter());
        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        tvSeekPass.setOnClickListener(this);
        editUserName.setOnFocusChangeListener(new MyFocusChangeLisenter());
        editUserPass.setOnFocusChangeListener(new MyFocusChangeLisenter());
        editUserName.addTextChangedListener(new HideTextWatcher(editUserName, 11));
        editUserPass.addTextChangedListener(new HideTextWatcher(editUserPass, 6));
        dbOpenHelper = new DBOpenHelper(MainActivity.this, "user.db", null, 1);
    }
    public void onClick(View view) {
        //登录按钮获取要查询的账号
        key = editUserName.getText().toString();
        cursor = dbOpenHelper.getReadableDatabase().query("user", null, "username = ?", new String[]{key}, null, null, null);
        //获取输入的密码框内容
        String etpassword = editUserPass.getText().toString();
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.loginButton:
                //创建ArrayList对象，用于保存用户数据结果
                ArrayList<Map<String, String>> resultList = new ArrayList<Map<String, String>>();//不用测试的话，直接遍历取值getstring（2）就行，创建数组可以省去。
                while (cursor.moveToNext()) {
                    //将结果集中的数据存入HashMap
                    Map<String, String> map = new HashMap<>();
                    //取出查询结果第二列和第三列的值
                    //用户名
                    map.put("username", cursor.getString(1));
                    //密码
                    map.put("password", cursor.getString(2));
                    resultList.add(map);

                    //获取数据库中符合用户名的对应的密码
                    dbpassword = map.get("password");
                }
                //正则化判断输入的账号是否符合手机号格式
                if (!isTelPhoneNumber(key)) {
                    Toast.makeText(MainActivity.this, "请输入正确的手机号！", Toast.LENGTH_SHORT).show();
                } else if (resultList == null || resultList.size() == 0) { //如果数据库中没有查询的用户数据
                    //显示提示信息，没有相关记录
                    Toast.makeText(MainActivity.this,
                            "该用户名未注册，请先注册", Toast.LENGTH_LONG).show();
                } else {
                    /*R.layout.userdata_main、R.id.result_name, R.id.result_grade
                这里的是我登录页面里面有个测试框用来显示数据库中符合输入的用户名的结果的
                等会写在下面把 只有一个userdata_main.xml */
                    SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, resultList,
                            R.layout.userdata_main, new String[]{"username", "password"}, new int[]{R.id.result_name, R.id.result_grade});
                    //将适配器和测试的listview关联，我这里的listview叫test_text
                    testListView.setAdapter(simpleAdapter);
                    //查到了用户 对比输入的密码与数据库的密码是否一致 如果相等跳转到主页面去
                    if (etpassword.equals(dbpassword)) {
                        Toast.makeText(MainActivity.this, "登陆成功！", Toast.LENGTH_SHORT).show();
                        //跳转到menuactivity
                        intent.setClass(MainActivity.this, menuActivity.class);
                        startActivity(intent);
                        //关闭登录页面
//                        MainActivity.this.finish();
                    } else {
                        Toast.makeText(MainActivity.this, "密码错误！", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case R.id.registerButton:

                //跳到注册页面后，需要携带注册数据返回登录页面
                intent.setClass(MainActivity.this, registerActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.seekBackPassword:
                if (key.length() < 11) {
                    Toast.makeText(this, "请输入正确的用户名！", Toast.LENGTH_SHORT).show();
                    return;
                }
                //跳转到找回密码页面
                intent.setClass(MainActivity.this, seekBackPasswordAcitivity.class);
                intent.putExtra("phoneNumber", key);
                startActivityForResult(intent, 1);
                break;
            default:
                break;
        }
    }

    /*正则化验证手机号码*/
    public static boolean isTelPhoneNumber(String mobile) {
        if (mobile != null && mobile.length() == 11) {
            Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]\\d{8}$");
            Matcher matcher = pattern.matcher(mobile);
            return matcher.matches();
        } else {
            return false;
        }
    }


    //setchecked :设置按钮勾选，stButtonDrawable：设置左侧勾选图标的图形资源
    //setOnCheckedChangeListener 设置勾选状态变化的监听器
    //isChecked:判断按钮是否勾选
    class MyCheckBoxLisenter implements CompoundButton.OnCheckedChangeListener {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                editUserPass.setText(key);
            }
        }
    }

    class MyFocusChangeLisenter implements View.OnFocusChangeListener {
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                switch (v.getId()) {
                    case R.id.userNameEditText:
                        String userName = editUserName.getText().toString();
                        if (TextUtils.isEmpty(userName) || userName.length() < 11) {
                            editUserName.requestFocus();
                            Toast.makeText(MainActivity.this, "请输入11位账户名", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case R.id.passwordEditText:
                        String userPassword = editUserPass.getText().toString();
                        if (TextUtils.isEmpty(userPassword) || userPassword.length() < 6) {
                            editUserPass.requestFocus();
                            Toast.makeText(MainActivity.this, "请输入6位密码", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        switch (resultCode) {
            //注册界面返回的数据
            case 2:
                Bundle bundle = data.getExtras();
                String userAccount = bundle.getString("userAccount");
                String userPassword = bundle.getString("userPassword");
                editUserName.setText(userAccount);
                editUserPass.setText(userPassword);
                break;
            //找回密码界面返回的数据
            case 3:
                String newUserPassword = data.getStringExtra("newPassword");
                editUserPass.setText(newUserPassword);
                break;
            default:
                break;
        }
    }

    private class HideTextWatcher implements TextWatcher {
        private EditText meditText;
        int maxLength;

        public HideTextWatcher(EditText editObject, int maxLength) {
            this.meditText = editObject;
            this.maxLength = maxLength;
        }

        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        public void afterTextChanged(Editable s) {
            String str = s.toString();
            if (str.length() == maxLength) {
                //隐藏输入法
                ViewUtil.hideOneInputMethod(MainActivity.this, meditText);
            }
        }
    }
}




